package com;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 * @auther Macrydy
 * @date 2020/7/17 10:31
 */
public class UploadServer{
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10086);

        while (true) {
            Socket accept = ss.accept();
            ServerThread ts = new ServerThread(accept);
            new Thread(ts).start();
        }
    }


}
class ServerThread implements Runnable{
    private Socket acceptSocket;

    public ServerThread(Socket accept) {
        this.acceptSocket=accept;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            //从通道缓冲区读入数据
            BufferedInputStream bis = new BufferedInputStream(acceptSocket.getInputStream());
            //本地的IO流,把数据写到本地中,实现永久化存储
            bos = new BufferedOutputStream(new FileOutputStream("D:\\" + UUID.randomUUID().toString() + ".jpg"));

            int b;
            while((b = bis.read()) !=-1){
                bos.write(b);
            }

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(acceptSocket.getOutputStream()));
            bw.write("服务器的反馈：文件上传成功");
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (acceptSocket != null){
                try {
                    acceptSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

